"use client";
import React, { useState, useRef } from "react";
import styles from "./login.module.css";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { signIn } from "next-auth/react";
import { toast, Toaster } from "react-hot-toast";

const Login = () => {
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState("");
  const [email, setEmail] = useState(""); // 新增：邮箱状态管理
  const [password, setPassword] = useState(""); // 新增：密码状态管理
  const [showPassword, setShowPassword] = useState(false); // 密码可见性
  const router = useRouter();

  const handleSubmit = async (e) => {
    e.preventDefault();
    setIsLoading(true);
    setError("");

    try {
      const result = await signIn("credentials", {
        email, // 使用状态中的邮箱
        password, // 使用状态中的密码
        redirect: false,
      });

      if (result.error) {
        setError(result.error || "登录失败，请检查邮箱或密码");
        toast.error(result.error || "登录失败");
      } else {
        toast.success("登录成功！");
        router.push("/dashboard");
        router.refresh();
      }
    } catch (err) {
      setError("网络错误，请稍后再试");
      toast.error("网络错误");
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className={styles.container}>
      <h1 className={styles.title}>登录</h1>
      <h2 className={styles.subtitle}>欢迎回来！请登录。</h2>

      <form
        onSubmit={handleSubmit}
        className={styles.form}
        autoComplete="off" // 禁用整个表单自动填充
      >
        {/* 邮箱输入框（禁用自动填充） */}
        <input
          type="email"
          name="email"
          placeholder="邮箱"
          required
          className={styles.input}
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          autoComplete="new-email" // 禁用邮箱自动填充
        />

        {/* 密码输入框（新增可见切换） */}
        <div className={styles.passwordContainer}>
          <input
            type={showPassword ? "text" : "password"} // 切换类型
            name="password"
            placeholder="密码"
            required
            className={styles.input}
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            autoComplete="new-password" // 禁用密码自动填充
          />
          {/* 密码可见切换按钮 */}
          <button
            type="button"
            onClick={() => setShowPassword(!showPassword)}
            className={styles.toggleBtn}
          >
            {/* {showPassword? "隐藏" : "显示"} */}
          </button>
        </div>

        <button
          type="submit"
          className={styles.button}
          disabled={isLoading}
        >
          {isLoading ? "登录中..." : "登录"}
        </button>

        {error && <p className={styles.error}>{error}</p>}
      </form>
      {/* 在登录按钮下方添加 */}
      <div className={styles.forgotLinkContainer}>
        <a
          href="/dashboard/forgot-password"
          className={styles.forgotLink}
        >
          忘记密码？
        </a>
      </div>
      <span className={styles.or}>
        还没有账号？
      </span>
      <Link className={styles.link} href="/dashboard/register">
        注册账号
      </Link>

      <Toaster position="top-right" />
    </div>
  );
};

export default Login;